package program.map;


import java.util.Objects;

/**
 * 使用链表实现map.
 *
 * 时间复杂度: O(n);
 * 都是基于getNode方法进行; 而最差的情况就是遍历所有情况.
 */
public class LinkedListMap<K, V> implements Map<K, V> {

    private class Node {
        public K key;
        public V value;

        public Node next;

        public Node() {
            this(null, null, null);
        }

        public Node(K key, V value) {
            this(key, value, null);
        }

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

        @Override
        public String toString() {
            return this.key.toString() + " : " + this.value.toString();
        }
    }

    private Node dummyHead;

    private int size;

    public LinkedListMap() {
        dummyHead = new Node();
        size = 0;
    }

    /**
     * map中key是唯一的.
     *
     * 若key已经存在的时候, 可以看成是更新.
     */
    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if (node == null) {
            // 在头节点位置插入
            dummyHead.next = new Node(key, value, dummyHead.next);
            size ++;
        } else {
            // 数据更新
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {
        Node pre = dummyHead;
        while (pre.next != null) {
            if (pre.next.key.equals(key)) {
                break;
            }

            pre = pre.next;
        }

        if (pre.next != null) {
            Node delNode = pre.next;
            pre.next = delNode.next;
            delNode.next = null;
            size --;
            return delNode.value;
        }

        return null;
    }

    @Override
    public boolean contains(K key) {
        Node node = getNode(key);
        return node != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node == null ? null : node.value;
    }

    @Override
    public V set(K key, V newValue) {
        Node node = getNode(key);
        if (Objects.isNull(node)) {
            throw new IllegalArgumentException("This key is error!");
        }

        V oldValue = node.value;
        node.value = newValue;
        return oldValue;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 查找key所在的Node节点
     */
    private Node getNode(K key) {
        Node cur = dummyHead.next;
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur;
            }

            cur = cur.next;
        }

        return null;
    }
}
